/*
 * @Author: C.
 * @Date: 2023-04-18 15:04:08
 */
import { onMounted, ref, onActivated, onDeactivated } from 'vue';
import { removeClass, addClass } from '/@/utils/domUtils';
import { throttle } from 'lodash-es';
import { useScrollTo } from '/@/hooks/event/useScrollTo';
export function usePageWrapperTabs(wrapperRef, isInner = false) {
  const tabOptionRef = ref<any[]>([]);
  const activeKey = ref(0);
  const scrollTop = ref<number>(0); // 记录当前的滚动距离
  const isScrolling = ref<boolean>(false);
  onMounted(() => {
    const option: any[] = [];
    const els = wrapperRef.value.getElementsByClassName(
      isInner ? 'jv-block-wrapper-inner' : 'jv-block-wrapper',
    );
    for (const el of els) {
      const obj = {
        title: el.getElementsByClassName('jv-block-title')[0].innerText,
        offset: el.offsetTop,
      };
      option.push(obj);
    }
    tabOptionRef.value = option;
  });
  async function tabChange(e, className = 'jv-wrapper-hover') {
    if (isInner) return;
    isScrolling.value = true;
    const el: HTMLDivElement = await wrapperRef.value.getElementsByClassName('jv-block-wrapper')[e];
    const offset = el.offsetTop - 70;
    const { start } = useScrollTo({
      el: document.body,
      to: offset,
      callback: () => {
        isScrolling.value = false;
      },
    });
    start();
    // document.body.scrollTop = offset;
    tabOptionRef.value[e].offset = offset;
    addClass(el, className);
    setTimeout(() => {
      removeClass(el, className);
    }, 1000);
  }
  function findClosestIndex(num, arr) {
    let minDiff = Infinity;
    let closestIndex = -1;
    for (let i = 0; i < arr.length; i++) {
      const diff = Math.abs(num - arr[i].offset);
      if (diff < minDiff) {
        minDiff = diff;
        closestIndex = i;
      }
    }
    return closestIndex;
  }
  // 1 3 5 7 9
  function findCurrentIndex(num, arr) {
    const cur_index = arr.findIndex((item) => item.offset >= num);

    return cur_index - 1;
  }
  function focusErrorBlock(offsetHeight: number) {
    const index = findCurrentIndex(offsetHeight, tabOptionRef.value);
    tabChange(index, 'jv-wrapper-error');
  }
  const setActive = throttle(() => {
    if (isScrolling.value) return;
    scrollTop.value = document.body.scrollTop;
    const offset = scrollTop.value + 10;
    activeKey.value = findClosestIndex(offset, tabOptionRef.value);
  }, 500);

  onActivated(() => {
    if (isInner) return;
    document.body.addEventListener('scroll', setActive);
  });
  onDeactivated(() => {
    if (isInner) return;
    document.body.removeEventListener('scroll', setActive);
  });
  return {
    tabOptionRef,
    activeKey,
    tabChange,
    focusErrorBlock,
  };
}
